<?php

declare(strict_types=1);
/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/5/24.
 */

namespace App\Models;

use App\Exceptions\CommonExceptionConstants;
use App\Exceptions\ServiceException;
use App\Models\Traits\ModelCache;
use App\Models\Traits\ModelField;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

/**
 * @property int id
 * @property int created_at
 * @property int updated_at
 */
class BaseModel extends Model
{
    use ModelCache;
    use ModelField;

    /**
     * @var array 间接性的关闭白名单
     */
    protected $guarded = ['id'];

    /**
     * 获取当前时间.
     */
    public function freshTimestamp(): int
    {
        return time();
    }

    /**
     * 避免转换时间戳为时间字符串.
     *
     * @param int $value
     *
     * @return int
     */
    public function fromDateTime($value): int
    {
        return $value;
    }

    /**
     * 从数据库获取的为获取时间戳格式.
     */
    public function getDateFormat(): string
    {
        return 'U';
    }

    public function getCreatedAtAttribute()
    {
        return date('Y-m-d H:i:s', $this->attributes['created_at']);
    }

    public function getUpdatedAtAttribute()
    {
        return date('Y-m-d H:i:s', $this->attributes['updated_at']);
    }

    /**
     * 设置每页显示数量.
     */
    public function getPerPage(): int
    {
        $limit = (int) (request()->get('limit', 20));
        if ($limit) {
            return $limit;
        }

        return parent::getPerPage();
    }

    public function getFillable(): array
    {
        if ($this->fillable) {
            return $this->fillable;
        }

        return $this->getTableFields();
    }

    /**
     * 获取单条数据，数据不存在抛出异常.
     *
     * @param $id
     *
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|Model
     */
    public static function byId($id)
    {
        $dao = (new static())->newQuery()->find($id);
        if (!$dao) {
            throw new ServiceException(CommonExceptionConstants::NO_FIND_DATA);
        }

        return $dao;
    }

    /**
     * 模型更新和新增时分别增加创建人、更新人.
     */
    protected static function booted(): void
    {
        // 新增前操作
        static::creating(function ($model): void {
            if (isset($model->fillable['creator_id'])) {
                $model->creator_id = Auth::guard(config('auth.app_guard_name'))->check()
                    ? Auth::guard(config('auth.app_guard_name'))->id() : 0;
            }
        });

        // 修改前操作
        static::updating(function ($model): void {
            if (isset($model->fillable['updater_id'])) {
                $model->updater_id = Auth::guard(config('auth.app_guard_name'))->check()
                    ? Auth::guard(config('auth.app_guard_name'))->id() : 0;
            }
        });
    }
}
